﻿#include "sig_proc.h"
#include "vol_acqu.h"
#include "slide_switch.h"
#include "sig_measure.h"
#include "queue.h"
#include "semphr.h"


#define SEN1_MAK (0x000000ffU) /* sen1掩码 */
#define SEN2_MAK (0x0000ff00U) /* sen2掩码 */

#define DEFAULT_FULL_SCALE (10U) /* 默认满量程为10mV */


/**
 * @brief 根据sen1和sen2开关的选择 求衰减倍数
 * @param sen1 满量程选择开关sen1的逻辑值
 * @param sen2 增益倍数选择开关sen2的逻辑值
 * @return 衰减倍数
 */
static uint16_t _GetAtten(uint8_t sen1, uint8_t sen2)
{
    uint16_t atten = 1;

    /* 选择满量程 */
    switch(sen1)
    {
    case SEN1_1V:
        atten *= 100;
        break;

    case SEN1_100mV:
        atten *= 10;
        break;

    case SEN1_10mV:
        atten *= 1;
        break;
    }

    /* 乘上增益倍数 */
    switch(sen2)
    {
    case SEN2_x5:
        atten *= 5;
        break;

    case SEN2_x2:
        atten *= 2;
        break;

    case SEN2_x1:
        atten *= 1;
        break;
    }

    return atten;
}


/**
 * @brief 信号处理任务
 * @param pvParameters 传递给任务的参数
 */
void SigProcTask(void *pvParameters)
{
    log("[info] SigProcTask start\n");

    SlideSwitch_t swValue ={ 0 }; // 滑动开关逻辑值

    uint16_t atten = 1; /* 衰减倍数 */

    BaseType_t isSend = pdFALSE; /* 是否发送成功 */

    Msg_t msg = { (MsgTopic_e)0 }; /* 发送给lcd的消息 */

    while(1)
    {
        /* 获取滑动开关逻辑值 */
        SlideSwitchGetValue(&swValue);

        // if(swValue.isUpdate)
        {
            /* 将cpl耦合选择开关逻辑值发送给LCD任务 */
            msg.msgData = swValue.cpl;
            msg.msgTopic = MSG_TOPIC_CPL;
            isSend = xQueueSend(msgQueueToLcdHandle, &msg, 0);
            // log("[print] cpl: %d, is send: %d\n", swValue.cpl, isSend);

            /* 计算衰减倍数并发送给lcd */
            atten = _GetAtten(swValue.sen1, swValue.sen2);
            msg.msgData = atten;
            msg.msgTopic = MSG_TOPIC_ATTEN;
            isSend = xQueueSend(msgQueueToLcdHandle, &msg, 0);
            // log("[print] atten: %d, is send: %d\n", atten, isSend);
        }

        log("[print] freq = %f, period = %f, duty = %f\n", SigMeasureGetFreq(), SigMeasureGetPeriod(), SigMeasureGetDuty());
        SigMeasureClear();

        /* 计算电压值并发送给lcd */
        float *vol = NULL;
        vol = VolAcquGetValue();
        if(vol == NULL) continue;
        for(uint8_t i = 0; i < ADC_BUFFER_LEN; i++)
        {
            vTaskSuspendAll();
            vol[i] *= atten;
            xTaskResumeAll();
            msg.msgData = (uint32_t)(vol[i] * 1000 + 0.5f); // 四舍五入后扩大一千倍
            msg.msgTopic = MSG_TOPIC_VOLTAGE;
            isSend = xQueueSend(msgQueueToLcdHandle, &msg, 0);
            log("voltage: %f\n", vol[i]);
        }
    }
}
